package cn.kpi.common.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateFormatUtils {
	public static Date convertStringToDate(String strDate) throws Exception {
		SimpleDateFormat df = null;
		Date date = null;
		df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date = df.parse(strDate);
		} catch (Exception ex) {

		}
		return (date);
	}

	public static Calendar getCalendar(String year,String month, int week) {
		try {
			Date newDate = convertStringToDate(year+"-"+month + "-01");
			Calendar caleNew = Calendar.getInstance();
			caleNew.setTime(newDate);
			caleNew.add(Calendar.WEEK_OF_MONTH, week - 1);
			return caleNew;
		} catch (Exception ex) {
			return null;
		}

	}

	/**
	 * 获取某月的第n星期的第一天
	 * 
	 * @param month:
	 *            2011-06
	 * @param week
	 *            : 2
	 * @return
	 */
	public static Date getFirstOfWeek(String year, String month, int week) {
		Calendar myCale = Calendar.getInstance();
		try {
			GregorianCalendar gc = (GregorianCalendar) getCalendar(year,month, week); // (GregorianCalendar)Calendar.getInstance();
			myCale.setTime(gc.getTime());
			myCale.set(Calendar.DATE, gc.get(Calendar.DATE) - gc.get(Calendar.DAY_OF_WEEK) + 2);
		} catch (Exception e) {

		}
		return myCale.getTime();
	}

	/**
	 * 获取某月的第n星期的最后一天
	 * 
	 * @param month:
	 *            2011-06
	 * @param week:
	 *            2
	 * @return
	 */
	public static Date getLastOfWeek(String year,String month, int week) {
		Calendar myCale = Calendar.getInstance();
		try {
			GregorianCalendar gc = (GregorianCalendar) getCalendar(year,month, week); // (GregorianCalendar)Calendar.getInstance();
			myCale.setTime(gc.getTime());
			myCale.set(Calendar.DATE, gc.get(Calendar.DATE) + 8 - gc.get(Calendar.DAY_OF_WEEK));

		} catch (Exception e) {

		}
		return myCale.getTime();

	}
	
	
	public static Date getLastOfMouth(String year,String month) {
		Calendar myCale = Calendar.getInstance();
		 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
		try {
			myCale.setTime(format.parse(year+"-"+month+"-01"));
			myCale.add(Calendar.MONTH, 1);  
			myCale.set(Calendar.DAY_OF_MONTH, 0);  

		} catch (Exception e) {

		}
		return myCale.getTime();
	}
}
